package com.fuyd.pms.background.rest.region;

import com.fuyd.pms.background.service.RegionService;
import com.fuyd.pms.dto.Result;
import com.fuyd.pms.dto.ResultCode;
import com.fuyd.pms.dto.v1.Province;
import com.fuyd.pms.dto.v1.RegionDto;
import com.fuyd.pms.utils.MediaTypes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 地区相关的api
 * 在Restful风格中，推荐使用http的状态码来表示请求的状态，本程序并未采用该做法。
 * Created by fuyongde on 2016/1/13.
 */
@RestController
@RequestMapping(value = "/api/regions")
public class RegionController {

    /**地区管理的service**/
    private RegionService regionService;

    @Autowired
    public void setRegionService(RegionService regionService) {
        this.regionService = regionService;
    }

    /**
     * 根据父级id，获取地区的详情
     * @param parentId 父级地区id
     * @return 地区详情
     */
    @RequestMapping(method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public Result regionList(@RequestParam(value = "parentId", defaultValue = "0") String parentId) {
        List<RegionDto> regionDtoList = regionService.findByParentId(parentId);
        if (regionDtoList == null || regionDtoList.size() == 0) {
            return new Result(ResultCode.CODE_REGION_NOT_FOUND);
        }
        return new Result(ResultCode.CODE_SUCCESS, regionDtoList);
    }

    /**
     * 获取地区的详情
     * @param id 地区id
     * @return 地区详情
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public Result regionInfo(@PathVariable("id") String id) {
        RegionDto regionDto = regionService.findById(id);
        if (regionDto == null) {
            return new Result(ResultCode.CODE_REGION_NOT_FOUND);
        }
        return new Result(ResultCode.CODE_SUCCESS, regionDto);
    }

    /**
     * 获取全部地区信息
     * @return 地区详情
     */
    @RequestMapping(value = "/all", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public Result regionAll() {
        List<Province> provinceList = regionService.findAll();
        if (provinceList == null || provinceList.size() == 0) {
            return new Result(ResultCode.CODE_REGION_NOT_FOUND);
        }
        return new Result(ResultCode.CODE_SUCCESS, provinceList);
    }

}
